package com.rockcent.mall;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.RequestUtils;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.MallRepository;
import com.rockcent.mall.lib.repository.MerchantRepository;
import com.rockcent.mall.lib.repository.UserMallRepository;
import com.rockcent.mall.lib.repository.UserMerchantRepository;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by oyhk on 15/11/29.
 * 用户可访问权限api
 */
@Component
public class UserPermissionInterceptor extends HandlerInterceptorAdapter {

    private final Logger log = LoggerFactory.getLogger(UserPermissionInterceptor.class);

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private MallRepository mallRepository;
    @Autowired
    private UserMallRepository userMallRepository;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MerchantRepository merchantRepository;
    @Autowired
    private UserMerchantRepository userMerchantRepository;

    private String userToken;


    public UserPermissionInterceptor(String userToken) {
        this.userToken = userToken;
    }

//    private List<String> merchantPermissionList = Arrays.asList("/merchant", "/market", "/mall/category", "/mall/logistics", "/mall/bank");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        String domain = RequestUtils.getDomain(request);
        //如果头部domain为空,在参数里面domain
        if (StringUtils.isBlank(domain)) {
            domain = request.getParameter("domain");
        }
        String userToken = request.getHeader(this.userToken);
        if (StringUtils.isBlank(userToken)) {
            userToken = RequestUtils.getStringParameter(request, this.userToken);
        }
        String userInfoId = stringRedisTemplate.boundValueOps(UserInfo.REDIS_USER_TOKEN_PREFIX + userToken).get();
        if (StringUtils.isBlank(userInfoId)) {
            response.getWriter().print(objectMapper.writeValueAsString(new JsonResult<>("10003", "user_token 无效")));
            response.getWriter().close();
            return false;
        }
        Long userId = new Long(userInfoId);

        //M端权限控制
        String mallId = stringRedisTemplate.boundValueOps(UserInfo.REDIS_MALL_LOGIN_PREFIX + userToken + "_" + domain).get();
        if (StringUtils.isNotEmpty(mallId)) {
            Mall mall = mallRepository.findById(new Long(mallId));
            if (mall == null) {
                response.getWriter().print(objectMapper.writeValueAsString(new JsonResult<>(JsonResult.CD_10104)));
                response.getWriter().close();
                return false;
            }
            UserMall userMalll = userMallRepository.findByMallIdAndUserId(mall.getId(), userId);
            if (userMalll == null) {
                response.getWriter().print(objectMapper.writeValueAsString(new JsonResult<>(JsonResult.CD_10105)));
                response.getWriter().close();
                return false;
            }
            if (userMalll.getAvailable() == null || userMalll.getAvailable() != Whether.YES) {
                response.getWriter().print(objectMapper.writeValueAsString(new JsonResult<>(JsonResult.CD_10106)));
                response.getWriter().close();
                return false;
            }
            //验证用户请求是否有权限,除了超级管理员
            if (userMalll.getIsSuperAdmin() != null && userMalll.getIsSuperAdmin() != Whether.YES) {
                String reqUri = request.getRequestURI();
                reqUri = reqUri.replace("v1", "");
                String backendUrl = stringRedisTemplate.boundValueOps(userToken + "-" + userMalll.getMallId() + "-" + reqUri).get();
                if (StringUtils.isEmpty(backendUrl)) {
                    response.getWriter().print(objectMapper.writeValueAsString(new JsonResult<>(JsonResult.CD_10105)));
                    response.getWriter().close();
                    return false;
                }
            }
            return true;
        }

        //M端权限控制
        String merchantId = stringRedisTemplate.boundValueOps(UserInfo.REDIS_MERCHANT_LOGIN_PREFIX + userToken + "_" + domain).get();
        if (StringUtils.isNotEmpty(mallId)) {
            Merchant merchant = merchantRepository.findOne(new Long(merchantId));
            if (merchant == null) {
                response.getWriter().print(objectMapper.writeValueAsString(new JsonResult<>(JsonResult.CD_10102)));
                response.getWriter().close();
                return false;
            }
            UserMerchant userMerchant = userMerchantRepository.findByUserIdAndMallIdAndMerchantId(userId, merchant.getMallId(), merchant.getId());
            if (userMerchant == null) {
                response.getWriter().print(objectMapper.writeValueAsString(new JsonResult<>(JsonResult.CD_10102)));
                response.getWriter().close();
                return false;
            }
            if (userMerchant.getAvailable() == null || userMerchant.getAvailable() != Whether.YES) {
                response.getWriter().print(objectMapper.writeValueAsString(new JsonResult<>(JsonResult.CD_10106)));
                response.getWriter().close();
                return false;
            }
            //验证用户请求是否有权限,除了超级管理员
            if (userMerchant.getIsSuperAdmin() != null && userMerchant.getIsSuperAdmin() != Whether.YES) {
                String reqUri = request.getRequestURI();
                reqUri = reqUri.replace("v1", "");
                log.info("======================>userToken:{},mallId:{},merchantId:{},reqUri:{}", userToken, userMerchant.getMallId(), userMerchant.getMerchantId(), reqUri);
                String backendUrl = stringRedisTemplate.boundValueOps(userToken + "-" + userMerchant.getMallId() + "-" + userMerchant.getMerchantId() + "-" + reqUri).get();
                if (StringUtils.isEmpty(backendUrl)) {
                    response.getWriter().print(objectMapper.writeValueAsString(new JsonResult<>(JsonResult.CD_10102)));
                    response.getWriter().close();
                    return false;
                }
            }
            return true;
        }
        return true;
    }

}
